package com.leilei.serviceProject.domain.strategy.service.rule.chain.impl;

import com.leilei.serviceProject.domain.strategy.model.entity.RaffleFactorEntity;
import com.leilei.serviceProject.domain.strategy.repository.IStrategyRepository;
import com.leilei.serviceProject.domain.strategy.service.armory.IStrategyDispatch;
import com.leilei.serviceProject.domain.strategy.service.rule.chain.AbstractLogicChain;
import com.leilei.serviceProject.types.common.Constants;
import com.leilei.serviceProject.types.enums.ResponseCode;
import com.leilei.serviceProject.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author yanglei
 * @description
 * @create 2024/11/12 23:38
 */
@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {
    @Resource
    private IStrategyRepository strategyRepository;
    @Resource
    private IStrategyDispatch strategyDispatch;

    public Long userScore = 0L;

    @Override
    public Integer logic(RaffleFactorEntity raffleFactorEntity) {
        // 4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109
        String ruleValue = strategyRepository.queryStrategyRuleEntity(raffleFactorEntity.getStrategyId(), raffleFactorEntity.getAwardId(),
                ruleModel());
        // ["4000:102,103,10...", "5000:102,103,10...", "6000:102,103,10..."]
        String[] ruleValueArray = ruleValue.split(Constants.SPACE);
        Map<Long, String> ruleValueMap = ruleValueArray2Map(ruleValueArray);
        // {4000 -> 4000:102,103,104,105, 6000 -> 6000:102,103,104,105,106,107,108,109, 5000 -> 5000:102,103,104,105,106,107}
        if (null == ruleValueMap || ruleValueMap.isEmpty()) {
            return next().logic(raffleFactorEntity);
        }
        // [4000, 5000, 6000]
        List<Long> ruleValueKeyList = new ArrayList<>(ruleValueMap.keySet());
        Collections.sort(ruleValueKeyList);
        // 4000 userScore大于4000取4000，大于5000、6000还是取4000这里有问题？
        Long scoreKey = ruleValueKeyList.stream().filter(key -> userScore >= key)
                .findFirst()
                .orElse(null);
        if (null != scoreKey) {
            Integer awardId = strategyDispatch.getRandomAwardId(raffleFactorEntity.getStrategyId(), ruleValueMap.get(scoreKey));
            log.info("抽奖责任链-权重接管:strategyId:{},userId:{},ruleModel:{},award:{}",raffleFactorEntity.getStrategyId()
                    ,raffleFactorEntity.getUserId(),ruleModel(),awardId);
            return awardId;
        }
        log.info("抽奖责任链-权重放行:strategyId:{},userId:{},ruleModel:{}",raffleFactorEntity.getStrategyId(),
                raffleFactorEntity.getUserId(),ruleModel());

        return next().logic(raffleFactorEntity);
    }

    public Map<Long, String> ruleValueArray2Map(String[] ruleValueArray) {
        Map<Long, String> ruleValueMap = new HashMap<>();
        for (String ruleValue : ruleValueArray) {
            if (null == ruleValue) {
                return ruleValueMap;
            }
            String[] ruleValueSplitArray = ruleValue.split(Constants.COLON);
            if (2 != ruleValueSplitArray.length) {
                throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_FORMAT_ERROR.getCode(),
                        ResponseCode.STRATEGY_RULE_WEIGHT_FORMAT_ERROR.getInfo());
            }
            ruleValueMap.put(Long.parseLong(ruleValue.split(Constants.COLON)[0]), ruleValue);
        }
        return ruleValueMap;
    }

    @Override
    protected String ruleModel() {
        return "rule_weight";
    }
}
